package cn.edu.sgu.www.mhxysy.service.system.impl;

import cn.edu.sgu.www.mhxysy.dto.system.EmailDTO;
import cn.edu.sgu.www.mhxysy.entity.system.Email;
import cn.edu.sgu.www.mhxysy.feign.clients.pms.PmsFeignService;
import cn.edu.sgu.www.mhxysy.redis.repository.impl.EmailRepository;
import cn.edu.sgu.www.mhxysy.restful.JsonResult;
import cn.edu.sgu.www.mhxysy.service.system.EmailService;
import cn.edu.sgu.www.mhxysy.util.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Service
public class EmailServiceImpl implements EmailService {

    private final EmailRepository emailRepository;
    private final PmsFeignService feignService;

    @Autowired
    public EmailServiceImpl(EmailRepository emailRepository, PmsFeignService feignService) {
        this.emailRepository = emailRepository;
        this.feignService = feignService;
    }

    @Override
    public void enable(Integer id) {
        feignService.enable(id);

        // 删除缓存
        emailRepository.deleteById(UserUtils.getUserId());
    }

    @Override
    public void insert(EmailDTO emailDTO) {
        emailDTO.setId(null);
        emailDTO.setUserId(UserUtils.getUserId());

        feignService.insertEmail(emailDTO);
    }

    @Override
    public void deleteById(Integer id) {
        feignService.deleteEmailById(id);
    }

    @Override
    public void updateById(EmailDTO emailDTO) {
        emailDTO.setUserId(UserUtils.getUserId());

        feignService.updateEmailById(emailDTO);
    }

    @Override
    public List<Email> selectByUserId() {
        String userId = UserUtils.getUserId();
        List<Email> list = emailRepository.selectById(userId);

        if(list == null) {
            JsonResult<List<Email>> jsonResult = feignService.selectEmailsByUserId(userId);

            if (jsonResult.isSuccess()) {
                list = jsonResult.getData();

                emailRepository.put(userId, list);
            }
        }

        return list;
    }

}